﻿using System.Collections.Generic;
using Dogshow.Model;
using DogshowRepository;
using System.Linq;

namespace Dogshow.Linq2SQLRepository
{
    public class RaseRepository : RepositoryBase, IRaseRepository
    {
        public int Sacuvaj(RasaPsa rasaPsa)
        {
            using (var model = new DogshowModel())
            {
                RasePasa r;
                if (rasaPsa.Id == 0)
                {
                    r = ModelMapper.Map(rasaPsa);
                    model.RasePasas.InsertOnSubmit(r);
                    model.SubmitChanges();
                }
                else
                {
                    r = model.RasePasas.Single(x => x.Id == rasaPsa.Id);
                    ModelMapper.Map(rasaPsa, r);
                    model.SubmitChanges();
                }
                return r.Id; 
            }
        }

        public IEnumerable<RasaPsa> VratiSve()
        {
            using (var model = new DogshowModel())
            {
                return model.RasePasas.Select(x => ModelMapper.Map(x)).ToArray(); 
            }
        }

        public RasaPsa VratiPoId(int id)
        {
            using (var model = new DogshowModel())
            {
                var r = model.RasePasas.SingleOrDefault(x => x.Id == id);
                if (r == null) return null;
                return ModelMapper.Map(r); 
            }
        }

        public IEnumerable<FciGrupa> VratiFciGrupe()
        {
            using (var model = new DogshowModel())
            {
                return model.FCIGrupes.Select(x => ModelMapper.Map(x)).ToArray(); 
            }
        }

        public IEnumerable<RasaPsa> FiltrirajPoDeluNaziva(string filter, int beginIndex, int endIndex)
        {
            using (var model = new DogshowModel())
            {
                var rase = model.RasePasas.AsQueryable();
                if (!string.IsNullOrEmpty(filter))
                {
                    rase = rase.Where(x => x.NazivRase.Contains(filter));
                }
                rase = rase.Skip(beginIndex).Take(endIndex - beginIndex + 1);
                return rase.Select(ModelMapper.Map).ToArray(); 
            }
        }
    }
}